from abc import ABC

from tornado.web import authenticated
from tornado.web import RequestHandler, url
from dbConnection.Mysql import Mysql
# 引入路由
from views.ViewRouterInterface import ViewRouterInterface
import os


# 登录方法
class LoginHandler(ViewRouterInterface, RequestHandler, ABC):

    # 获取动态设置的参数(greeting,info)
    def initialize(self, greeting, info):  # 动态参数要与url路由中设置的参数必须一样
        print("##############调用了初始化方法：initialize()##################")
        self.greeting = greeting
        self.info = info

    # 配置路由
    def configRouter(self):
        return [
            # 加上url之后，我们就可以为url设置一个name属性
            url('/login', LoginHandler, {'greeting': '参数1', 'info': '参数2'}, name='login_url')
        ]

    # 由于使用了装饰器tornado.web.authenticated，需要重写get_current_user()
    # 用于校验用户登录信息，此处返回False进行登录拦截
    def get_current_user(self):
        # 此处用于完成验证用户信息
        f = True
        if f:
            return True
        else:
            return False

    # 权限校验装饰器
    @authenticated
    def get(self):
        next_url = self.get_argument("next", "/")
        if next_url:
            print(next_url)
            self.redirect(next_url + "?f=login")
        else:
            self.write("登陆页面")

    def post(self, *args, **kwargs):
        u_name = self.get_body_argument('name')
        password = self.get_body_argument('password')
        print('用户名: ', u_name, ' , 密码:', password)

        files = self.request.files
        # 明确知道用户就上传了一张图片时
        # 用下标的方式将这唯一一张图片直接取出
        avatar = files.get('avatar')[0]
        filename = avatar.get('filename')
        body = avatar.get('body')
        if not os.path.exists('upload'):
            os.mkdir('upload')
        # 持久化数据
        sql = "INSERT INTO test(name, age, path) values (%s, %s, %s)"
        print(sql)
        db = Mysql()
        db.insertOne(sql, (u_name, 20, 'upload/' + filename))
        writer = open('upload/%s' % filename, 'wb')
        writer.write(body)
        writer.close()
        self.render('index.html', name=u_name)
